import {
	calcAmount,
	setItem,
	getItem,
	fmtBalance,
	Decimals,
	message,
	fmtBalanceDecimal,
	getCurrencyIcon
} from '@/utils'
import router from '@/router'
import { useWalletStore } from '@/store'
import { currencyPrecision, CurrencyEnum } from '@/enums'

export function transferToNumber(inputNumber: any) {
	if (isNaN(inputNumber)) {
		return inputNumber
	}
	inputNumber = '' + inputNumber
	// 检查是否有小数部分
	const [, decimalPart] = inputNumber.split('.')
	const decimalPlaces = decimalPart ? decimalPart.length : 0
	inputNumber = parseFloat(inputNumber)
	const eformat = inputNumber.toExponential() // 转换为标准的科学计数法形式（字符串）
	const tmpArray = eformat.match(/\d(?:\.(\d*))?e([+-]\d+)/) // 分离出小数值和指数值
	const number = inputNumber.toFixed(Math.max(0, (tmpArray[1] || '').length - tmpArray[2]))
	if (Number(number) === 0 && decimalPlaces > 0) {
		return Number(number).toFixed(decimalPlaces)
	}
	return number
}

export const transformationAmount = (amount: any) => {
	const { balanceCur, walletConfig } = useWalletStore()
	if (balanceCur?.currency && walletConfig.displayCryptoInFiat) {
		const comp = calcAmount(amount, balanceCur.currency, undefined, true)
		return comp.amount
	}
	return amount || 0
}

export const getDecimalPlaces = (currency?: CurrencyEnum): number => {
	const { balanceCur, fiatOrFalse } = useWalletStore()
	const cur = (currency || fiatOrFalse || balanceCur?.currency) as CurrencyEnum
	return currencyPrecision[cur] ?? 8
}

// 获取游戏缓存名称
export const getGameCacheName = () => {
	const route = router.currentRoute.value
	const id = route.path?.split('/').pop()
	if (id) {
		return `${id}CacheData`
	}
	return ''
}

// 获取游戏缓存值
export const getGameCacheData = () => {
	const data = getItem(getGameCacheName())
	return data ? data : {}
}

// 设置游戏缓存值
export const setGameCacheData = (uData: any) => {
	let data = getItem(getGameCacheName())
	data = data ? data : {}
	const newData = { ...data, ...uData }
	setItem(getGameCacheName(), newData)
}

// 获取法币开启时的标志
export const getFiatlg = (amount = 0): string => {
	const { walletConfig, balanceCur } = useWalletStore()
	let currencySymbol = ''
	if (walletConfig?.displayCryptoInFiat && balanceCur?.currency) {
		const comp = calcAmount(amount, balanceCur.currency, undefined, false)
		currencySymbol = comp.currencySymbol
	}

	return currencySymbol
}

/**
 * 将时间戳转换为指定格式的日期字符串
 * @param {number} timestamp - 时间戳（毫秒）
 * @returns {string} - 格式化的日期字符串
 */
export function formatTimestamp(timestamp: number): string {
	if (!timestamp) return ''
	// 创建 Date 对象
	const date = new Date(timestamp)

	// 获取年、月、日、小时、分钟和秒
	const year = date.getFullYear()
	const month = date.toLocaleString('en-US', { month: 'long' })
	const day = date.getDate()
	const hours = date.getHours()
	const minutes = date.getMinutes()

	// 将小时转换为12小时制
	const hour12 = hours % 12 || 12
	const amPm = hours >= 12 ? 'PM' : 'AM'

	// 格式化分钟，确保两位数
	const formattedMinutes = minutes < 10 ? `0${minutes}` : minutes

	// 拼接成所需的格式
	const formattedDate = `on ${month} ${day}, ${year} (${hour12}:${formattedMinutes} ${amPm})`

	return formattedDate
}
// 生成10个随机数
function generateRandomString(length: number) {
	const charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
	let result = ''
	for (let i = 0; i < length; i++) {
		const randomIndex = Math.floor(Math.random() * charset.length)
		result += charset[randomIndex]
	}
	return result
}

export function generateFormattedString(totalLength: number) {
	const includeHyphen = Math.random() < 0.5 // 50% 的概率包含连字符

	if (includeHyphen) {
		// 确保连字符不在开头和结尾
		const minHyphenPosition = 1
		const maxHyphenPosition = totalLength - 2
		const hyphenPosition =
			Math.floor(Math.random() * (maxHyphenPosition - minHyphenPosition + 1)) + minHyphenPosition

		const part1Length = hyphenPosition
		const part2Length = totalLength - part1Length - 1

		const part1 = generateRandomString(part1Length)
		const part2 = generateRandomString(part2Length)

		return `${part1}-${part2}`
	} else {
		return generateRandomString(totalLength)
	}
}

// 赔付的提示框悬停事件
export const resultSquareClick = (multiplier: any, amount: string | number) => {
	const { balanceCur, fiatOrFalse, walletConfig } = useWalletStore()
	const { displayCryptoInFiat, selectedFiatCurrency, selectedCryptoCurrency } = walletConfig || {}
	if (balanceCur?.currency) {
		const profit = Decimals.sub(Decimals.mul(amount, multiplier), amount)
		const comp = calcAmount(profit, fiatOrFalse || balanceCur.currency)
		const compFait = calcAmount(profit, balanceCur.currency, undefined, true)
		const obj = {
			profit: fmtBalance(comp.amount, comp.currencyTo),
			currency: `${compFait.currencySymbol} ${fmtBalance(compFait.amount, compFait.currencyTo)}`,
			currencyIcon: getCurrencyIcon(
				displayCryptoInFiat ? selectedFiatCurrency : selectedCryptoCurrency
			)
		}
		return JSON.stringify(obj)
	}
	return '{"profit": "1000", "currency": "10000.00ETH", "currencyIcon": "https://d11njdywhf5zo.cloudfront.net/test-2up/2024/10/21/bba9b4fc289e43edbb939c597331ab0c.png"}'
}

// 游戏结果利润换算
export const clacProfit = (data: any) => {
	const profit = Decimals.sub(data.payout, data.amount)
	const comp = calcAmount(profit, data.currency)
	const m = fmtBalance(comp.amount, comp.currencyTo)
	return `${comp.currencySymbol} ${m}`
}

// 计算盈亏暂停自动投注
export const calculateProfitLoss = (data: any, params: any): boolean => {
	const { type, amount, profitPer, lossPer, profit, loss, profitLossTotal, autoOneAmount } = params
	if (type.value !== 'auto') return false
	const { payout, amount: bAmount, currency } = data
	const { value: profitPerVal, active: profitPerActive } = profitPer.value
	const { value: lossPerVal, active: lossPerActive } = lossPer.value
	// 计算赢了还是输了
	const resProfit = Decimals.sub(payout, bAmount)
	const comp = calcAmount(resProfit, currency)
	const winningLosing = Number(fmtBalanceDecimal(comp.amount, comp.currencyTo))
	profitLossTotal.value = Decimals.add(profitLossTotal.value, winningLosing)
	const nAmount = Number(amount.value)
	const nProfitPer = Number(profitPerVal)
	const nLossPer = Number(lossPerVal)
	const nProfit = Number(profit.value)
	const nLoss = Number(loss.value)
	if (winningLosing > 0) {
		if (profitPerActive === 'rest') {
			// 赢了重置
			amount.value = autoOneAmount.value
		} else {
			if (nProfitPer) {
				// 赢了加上增幅
				const w = Decimals.add(nAmount, nAmount * (nProfitPer / 100))
				amount.value = transferToNumber(parseFloat(w.toFixed(getDecimalPlaces())))
			}
		}
	} else {
		if (lossPerActive === 'rest') {
			//输了重置
			amount.value = autoOneAmount.value
		} else {
			if (nLossPer) {
				// 输了加上亏损增幅
				const l = Decimals.add(nAmount, nAmount * (nLossPer / 100))
				amount.value = transferToNumber(parseFloat(l.toFixed(getDecimalPlaces())))
			}
		}
	}
	console.log(profitLossTotal.value, winningLosing, nProfit, nLoss, 'profitLossTotal')
	// 累计盈利亏损是否达到阈值
	if (profitLossTotal.value > 0 && nProfit && profitLossTotal.value >= nProfit) {
		message.success('自动投注完成, 已达到止盈', { duration: 5000 })
		return true
	}
	if (profitLossTotal.value < 0 && nLoss && Math.abs(profitLossTotal.value) >= nLoss) {
		message.success('自动投注完成, 已达到止损', { duration: 5000 })
		return true
	}
	return false
}
